package com.mg.yygh.msm.controller;

import com.mg.yygh.common.result.Result;
import com.mg.yygh.msm.service.MsmService;
import com.mg.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.concurrent.TimeUnit;

/**
 * @author M_Dragon
 * @date 2022/9/7/007 23:36
 */
@Api(tags = "短信发送")
@RestController
@RequestMapping("/api/msm")
public class MsmApiController {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private MsmService msmService;


    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable("phone") String phone){

        // 从redis获取验证码
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)){
            return Result.ok();
        }

        // 随机生成验证码
        code = RandomUtil.getFourBitRandom();

        // 发送验证码
        boolean isSend = msmService.sendCode(phone,code);

        // 将验证码放入redis限制时间
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            return Result.ok();
        }else {
            return Result.fail("短信发送失败！！！");
        }
    }
}
